package com.lmx.project.untils;

import com.lmx.project.common.BaseResponse;
import com.lmx.project.common.ErrorCode;
import com.lmx.project.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class FileUtilAsync {
    @Value("${myfile.pre}")
    private String pre;

//    @Value("${myfile.preurl}")
//    private String preurl;

    @Resource
    private RestTemplate restTemplate;

    @Value("${resourse.url}")
    private String resourseurl;

    /**
     * 将输入流保存到指定路径的文件中
     *
     * @param inputStream 输入流
     * @param path        文件保存的路径，包括文件名
     * @throws IOException 如果写入文件时发生I/O错误，则会抛出IOException
     */
//    @Async


    /**
     * 将文件上传到服务器，并删除原始文件
     */
//    @Async
    public void uploadNetwork(String path, File file) {
        try {
            //        将文件上传到文件服务器
            String realpath = pre + path;

            File netfile = new File(realpath);

            // 1、封装请求头
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("multipart/form-data");
            headers.setContentType(type);
            headers.setContentLength(file.length());
            headers.setContentDispositionFormData("media", file.getName());


            // 2、封装请求体
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            FileSystemResource resource = new FileSystemResource(netfile);
            param.add("file", resource);
            param.add("dir", path);

            // 3、封装整个请求报文
            HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(param, headers);
            // 4、发送请求
            ResponseEntity<BaseResponse> data = restTemplate.postForEntity(resourseurl + "file", formEntity, BaseResponse.class);
//            System.out.println("返回的结果是" + data.getBody());

            BaseResponse body = data.getBody();
            if (data.getStatusCode() == HttpStatus.OK) {
                if (body.getCode() == 0) {

                    //     删除临时文件
//            System.out.println(""+netfile.getAbsolutePath());
                    boolean delete = netfile.delete();
//                    if (!delete) {
//                        throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件删除失败，请重试");
//                    }

                } else {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, body.getMessage());
                }
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件服务异常");
            }
//            System.out.println("保存文件成功：" + path);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件保存失败");
        }

    }


    /**
     * 删除文件
     */
//    @Async
    public void removeFile(String path) {

        if (!StringUtils.isNotBlank(path)) {
            return;
        }
//        String realpath = pre + path;
//        System.out.println(realpath);
//        File file = new File(realpath);
// 发送请求删除文件
//        HashMap<String, Object> uriVariables = new HashMap<>();
//        uriVariables.put("filepath", path);
//        HttpHeaders headers = new HttpHeaders();
//        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//        headers.setContentType(type);
//        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//
//        ArrayList<Object> similarList = new ArrayList<>();
//        similarList.add("1");
//        similarList.add("2");
//        similarList.add("3");

        try {
            HttpEntity<String> entity = new HttpEntity<>(path);

            ResponseEntity<BaseResponse> baseResponseResponseEntity = restTemplate.postForEntity(resourseurl + "file/delete", entity, BaseResponse.class);
            if (baseResponseResponseEntity.getStatusCode() == HttpStatus.OK) {
                if (baseResponseResponseEntity.getBody().getCode() == 0) {
                    System.out.println("删除成功");
                }
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件服务异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }


//        boolean delete = file.delete();
//        if (!delete) {
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片删除失败，请重试");
//        }

    }

    /**
     * 保存文件，绝对路径
     */
//    @Async
    public void saveFile(InputStream inputStream, String absolutePath) throws IOException {
        absolutePath = pre + absolutePath;
        System.out.println(absolutePath + "开始保存");
        File file = new File(absolutePath);

        if (file.getParentFile() != null && !file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        FileOutputStream outputStream = new FileOutputStream(file);

        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }

        inputStream.close();
        outputStream.close();
        System.out.println(absolutePath + "保存完毕");

    }

    /**
     * 获取url路径
     */
    public String getPreUrl() {
        try {
            BaseResponse forObject = restTemplate.getForObject(resourseurl + "file/pre", BaseResponse.class);

            if (forObject.getCode() == 0) {
                return (String) forObject.getData();
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }


    }
}
